import axios from 'axios'
import jwt_decode from 'jwt-decode'
import { GET_ERRORS, SET_CURRENT_USER } from './types'
import setAuthToken from '../utils/setAuthToken'
// 注册
export const registerUser = (userData, history) => dispatch => {
  axios.post('/api/users/register', userData).then(res => {
    // 路由跳转
    history.push('/login')
  }).catch(err => {
    console.log(err);

    dispatch(
      { type: GET_ERRORS, payload: err.response.data }
    )
  })
}
// 登录 
export const loginUser = (userData) => dispatch => {
  axios.post('/api/users/login', userData).then(res => {
    let { token } = res.data;
    localStorage.setItem('jwtToken', token)
    // 设置token到头部
    setAuthToken(token)
    // 解析token
    const decoded = jwt_decode(token)
    dispatch(setCurrentUser(decoded))

  }).catch(err => dispatch(
    { type: GET_ERRORS, payload: err.response.data }
  ))
}
// 返回解析后把token提交给redux
export const setCurrentUser = (decoded) => {
  return {
    type: SET_CURRENT_USER,
    payload: decoded
  }

}
// 退出
export const logoutUser = () => dispatch => {
  localStorage.removeItem('jwtToken')
  // 清楚头部信息
  setAuthToken(false)
  // 派发到reducer
  dispatch(setCurrentUser({}))
}
